// components/pl/pl.js



import {
    upload_img,
    getEmojis
} from '../../api/shool/get_score.js'
import formDate from '../../utils/formDate.js'
Component({
    /**
     * 组件的属性列表
     */
    properties: {

        text_type: String,
        pl_data: Object,
        pl_type: String,
        ly_pl_data: Object,

        emol_open_is: String



    },


    /**
     * 组件的初始数据
     */
    data: {
        updata_num: 0,

        emol_list: [],
        jianpan: false,
        pl_data: null,
        fileList: [],
        message: '',
        user_info: wx.getStorageSync('user'),
        wx_info: wx.getStorageSync('wx_user_info'),
        emol_index: 0,
        is_emol: false,
        text_type: 'false',
        emol_textlist: [],
        is_up: false,

        checked: false,
        text_height: 150,

        jianpan_is: false,
        focus_is: false,

    },
    observers: {
        'text_type'(val) {

            if (val == 'true') {
                if (this.data.emol_open_is != 'true') {
                    setTimeout(() => {
                        this.data.jianpan_is = true
                        this.setData({
                            jianpan_is: true,
                            focus_is: 'auto'
                        })

                    }, 500)

                }

            } else {
                this.setData({
                    // text_type: false,
                    jianpan_is: false,
                    focus_is: false,
                    text_height: 150
                })
            }
        },
        'emol_list'(val) {

        },
        'emol_open_is'(val) {
            if (val == 'true') {
                this.get_emojis()
                this.setData({
                    is_emol: true,
                    jianpan_is: false,
                    focus_is: false
                })
            } else {
                this.setData({
                    is_emol: false,


                })
            }
        },
        'jianpan_is'(val) {
            console.log(val)
            if (val == 'true') {
                this.setData({
                    text_height: 300
                })
            } else {
                this.setData({
                    text_height: 150
                })
            }
        }
    },

    /**
     * 组件的方法列表
     */
    methods: {
        //点击聚焦
        jujiao() {
            if (this.data.jianpan_is) {
                this.setData({
                    jianpan_is: false,
                    focus_is: false
                })
            } else {
                this.setData({
                    focus_is: 'auto',
                    jianpan_is: true

                })
            }

        },


        //解码
        html_decode(str) {
            var patt = /[\ud800-\udbff][\udc00-\udfff]/g; // 检测utf16字符正则 
            str = str.replace(patt, function (char) {
                var H, L, code;
                if (char.length === 2) {
                    H = char.charCodeAt(0); // 取出高位 
                    L = char.charCodeAt(1); // 取出低位 
                    code = (H - 0xD800) * 0x400 + 0x10000 + L - 0xDC00; // 转换算法 
                    return "&#" + code + ";";
                } else {
                    return char;
                }
            });
            return str;
        },

        onChange({
            detail
        }) {
            // 需要手动对 checked 状态进行更新
            this.setData({
                checked: detail
            });
        },

        //生成评论
        create_comment: function (e) {
            //遍历this.data.message字符串，查找emoji表情和文字


            let str = this.data.message;
            var reg = /\[(.*?)\]/ig;
            var text = /\](.*?)\[/ig;
            let arr = str.match(reg) || [];
            let str_1 = str.match(text) || [];
            let str_0 = '';
            let str_2 = '';
            for (var i = 0; i < str.length; i++) {
                if (str[i] != '[') {
                    str_0 += str[i]
                } else {
                    break;
                }
            }
            for (var i = str.length - 1; i > 0; i--) {
                if (str[i] != ']' && i != 1) {
                    str_2 += str[i]
                } else if (i == 1) {
                    str_2 = ''

                } else {
                    break
                }
            }
            let i_1 = 0;
            if (str_0 != '') {
                //头插
                arr.unshift(str_0)
                i_1++
            }


            for (let i = 0; i < str_1.length; i++) {

                if (str_1[i] != '][') {
                    let aeg = str_1[i].replace(/\[|\]/ig, '')
                    //插入到arr指定位置
                    arr.splice(i + 1 + i_1, 0, aeg)
                    i_1++
                }
            }
            if (str_2 != '') {
                //尾插
                //反转
                str_2 = str_2.split('').reverse().join('')
                arr.push(str_2)
            }

            let data_list = []

            //对比[]是否想的正则表达式
            let reg_1 = /\[|\]/;





            //识别换行
            let reg_2 = /\n/;


            for (let i = 0; i < arr.length; i++) {
                //去掉arr中的[]

                if (reg_1.test(arr[i])) {

                    //查找对应的url
                    let url = '';
                    this.data.emol_textlist.forEach(function (item, index) {
                        let url_1 = item.url
                        arr[i] = arr[i].replace(/\[|\]/ig, '')

                        if (item.name == arr[i]) {
                            url = url_1
                        }
                    })

                    data_list.push({
                        //查找对应的url
                        name: 'img',
                        attrs: {
                            src: url,
                            width: this.data.pl_type == '3' ? '20rpx' : '25rpx',
                            height: this.data.pl_type == '3' ? '20rpx' : '25rpx',

                        },
                    })
                } else {

                    let arr_str = ''
                    for (let j = 0; j < arr[i].length; j++) {

                        if (reg_2.test(arr[i][j])) {
                            data_list.push({
                                name: 'br',
                                attrs: {},
                            })
                        } else {
                            arr_str = arr[i][j]
                            data_list.push({

                                type: 'text',
                                decode: true,
                                text: arr_str,
                                style: 'color: #000;font-size: 30rpx; word-break: break-word;'

                            })

                        }
                    }
                }

            }

            let img_value = [];
            if (this.data.fileList.length > 0) {
                for (let i = 0; i < this.data.fileList.length; i++) {

                    img_value.push({
                        id: null,
                        lid: null,
                        url: this.data.fileList[i].url_1
                    })

                }

            } else {
                img_value.push({
                    id: null,
                    lid: null,
                    url: null
                })

            }



            let user = null




            let wx_info = wx.getStorageSync('wx_user_info')
            let openid = wx.getStorageSync('openid')
            let user_web = wx.getStorageSync('user')
            let userInfo = wx.getStorageSync('userinfo')
            let app = getApp()

            if (!userInfo.avatar) {
                userInfo.avatar = userInfo.sex.value == '男' ? 'https://s2.loli.net/2022/04/25/BsjiZuH1R6nrxS8.png' : 'https://s2.loli.net/2022/04/25/wMOugULePhsdYcp.png'
            }

            if (this.data.pl_type == '1') {
                user = {
                    // "id": "随便",
                    "retweets": openid,
                    "userId": openid,
                    "userNickname": this.data.checked ? '匿名用户' : wx_info.nickName,
                    "userAvatar": this.data.checked ? 'https://s2.loli.net/2022/04/09/rgPV5bX3aASwB6q.png' : userInfo.avatar,
                    "userSex": userInfo.sex.value == '男' ? '1' : '0',
                    "id": "随便",
                    "ifPublic": this.data.checked ? "1" : "0",
                    "phoneModel": app.globalData.phone_info.platform,
                    "contentColor": "绿色",
                    "readCount": "0",
                    "ifAdmin": user_web.type == 1 ? '1' : "0",
                    "address": "湖北省武汉市",
                    "ip": "0",


                }

                user.leaveMessageImgs = img_value
                user.content = JSON.stringify(data_list)



            } else if (this.data.pl_type == '2') {

                user = {
                    "id": "随便",
                    "userId": openid,

                    "belongId": this.data.pl_data.id,
                    "replyCount": "0",
                    "nickName": !this.data.checked ? this.html_decode(wx_info.nickName) : '匿名用户',
                    "avatar": !this.data.checked ? userInfo.avatar : 'https://s2.loli.net/2022/04/09/rgPV5bX3aASwB6q.png',
                    "status": 1,
                    "sex": userInfo.sex.value == '男' ? '1' : '0',
                    "ifPublic": this.data.checked ? "1" : "0",
                    "retweets": openid,
                    "phoneModel": app.globalData.phone_info.platform,
                    "contentColor": "绿色",
                    "readCount": "0",
                    "ifAdmin": user_web.type == 1 ? '1' : "0",
                    "address": "随便",
                    "ip": "0",
                    "phone": "随便"
                }
                user.content = JSON.stringify(data_list)



            } else {
                user = {
                    "id": "随便",
                    "commentId": this.data.ly_pl_data.id,
                    "fromUserId": openid,
                    "toUserId": this.data.ly_pl_data.fromUserId,

                    "status": "1",
                    "fromUserNickname": !this.data.checked ? this.html_decode(wx_info.nickName) : '匿名用户',
                    "fromUserAvatar": !this.data.checked ? userInfo.avatar : 'https://s2.loli.net/2022/04/09/rgPV5bX3aASwB6q.png',
                    "toUserNickname": this.html_decode(this.data.ly_pl_data.nickname || this.data.ly_pl_data.fromUserNickname),
                    "toUserAvatar": this.data.ly_pl_data.userAvatar || this.data.ly_pl_data.fromUserAvatar,
                    "fromUserSex": userInfo.sex.value == '男' ? '1' : '0',
                    "fromUserPhoneModel": app.globalData.phone_info.platform,
                    "fromUserIfAdmin": user_web.type == 1 ? '1' : "0",
                    "toUserSex": this.data.ly_pl_data.sex || this.data.ly_pl_data.fromUserSex,
                    "toUserPhoneModel": this.data.ly_pl_data.phoneModel || this.data.ly_pl_data.fromUserPhoneModel,
                    "toUserIfAdmin": this.data.ly_pl_data.ifAdmin || this.data.ly_pl_data.fromUserIfAdmin
                }
                user.content = JSON.stringify(data_list)
            }





            let is_1 = null
            let is_2 = null
            if (this.data.pl_type == '1') {
                is_2 = user.leaveMessageImgs[0].url != null
                console.log(JSON.parse(user.content))
                if (user.content != "[]") {
                    //遍历是否都为br
                    let arr = JSON.parse(user.content)
                    for (let i = 0; i < arr.length; i++) {
                        if (arr[i].name == "br" || arr[i].text == " ") {
                            is_1 = false
                            console.log(arr[i].name)
                        } else {
                            is_1 = true
                            console.log(arr[i])
                            break
                        }
                    }
                } else {
                    is_1 = false
                }
            } else {
                is_2 = false
                if (user.content != "[]") {
                    //遍历是否都为br
                    let arr = JSON.parse(user.content)
                    for (let i = 0; i < arr.length; i++) {
                        if (arr[i].name == "br" || arr[i].text == " ") {
                            is_1 = false
                            console.log(arr[i].name)
                        } else {
                            is_1 = true
                            console.log(arr[i])
                            break
                        }
                    }
                } else {
                    is_1 = false
                }

            }


            if (is_1 || is_2) {
                user.type = '1'
                if (this.data.updata_num <= 0||this.data.fileList.length==0) {
                    this.data.fileList = []
                    this.data.message = '',
                        this.data.emol_textlist = []
                    this.triggerEvent('create_comment', user)
                    this.setData({

                        text_type: 'false',
                        is_emol: false,
                        message: '',
                        fileList: [],

                    })
                } else {
                    wx.showToast({
                        title: '请等待图片上传完毕!',
                        icon: 'none',
                        duration: 3000
                    })
                }


            } else {


                wx.showToast({
                    title: '请输入评论内容',
                    icon: 'none',
                    duration: 2000
                })
                //关闭遮罩层
                user.type = '2'
                // if(this.data.updata_num==0){
                //     this.triggerEvent('create_comment', user)  
                //     this.setData({

                //         text_type: 'false',
                //         is_emol: false,
                //         message: '',
                //         fileList: [],

                //     })
                //   }else{
                //       wx.showToast({
                //           title: '请等待图片上传完毕!',
                //           icon: 'none',
                //           duration: 3000
                //       })
                //   }

            }



        },

        // //发送留言
        // pushMessage_ly(data){
        //     pushMessage_ly(data).then(res => {
        //          
        //     })
        // },
        //获取焦点
        focus_up(e) {


            this.setData({

                text_height: e.detail.height + 300
            })

        },

        focus_down() {
            this.data.jianpan_is = false
            this.setData({
                jianpan_is: false,
                text_height: 150
            })
        },
        json2Form(json) {
            var str = [];
            for (var p in json) {
                str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p]));
            }
            return str.join("&");
        },


        //上传图片
        afterRead(e) {
            let that = this
            let {
                fileList = []
            } = this.data
            let {
                file
            } = e.detail

            file.map(item => {
                let data = null
                let is_1 = item.size > 1024 * 1024 * 3
                let is_2 = item.type != 'image'
                if (item.size > 1024 * 1024 * 3) {
                    wx.showToast({
                        title: '图片大小不能超过3M',
                        icon: 'none',
                        duration: 2000
                    })
                    return
                }

                if (item.type != 'image') {
                    wx.showToast({
                        title: '图片格式不正确',
                        icon: 'none',
                        duration: 2000
                    })
                    return
                }
                if (!is_1 && !is_2) {
                    fileList.push({
                        url: item.url,
                        message: '上传中...',
                        status: 'uploading'

                    })
                    that.setData({
                        fileList
                    })
                }






            })
            setTimeout(() => {
                // let that=this
                fileList.map((item, index) => {

                    //获取本 地路径文件的方法
                    this.data.updata_num++
                    if (item.status == 'uploading') {

                        wx.uploadFile({
                            url: 'https://d.flya.top:31193/comment/uploadLeaveImgs', //仅为示例，非真实的接口地址
                            filePath: item.url,
                            name: 'files',
                            header: {
                                'content-type': 'multipart/form-data',
                                Authorization: wx.getStorageSync('token')
                            },

                            success(res) {
                                const data = JSON.parse(res.data)
                                //do something


                                if (data.statusCode == 200) {
                                    that.data.updata_num--
                                    item.status = 'success'
                                    item.message = '上传成功'
                                    item.url = item.url
                                    item.url_1 = data.data[0]

                                } else {
                                    that.data.updata_num--
                                    item.status = 'failed'
                                    item.message = '上传失败'
                                    item.url = null
                                }

                                that.data.fileList[index] = item
                                that.setData({
                                    fileList: that.data.fileList
                                })

                            }
                        })



                    }


                })



            }, 1000)



        },



        //删除表情
        emol_del() {
            //删除this.data.emol_textlist最后一项

            //字符截取

            var reg = /\[(\d+)\]/ig;
            var text = /\[(.*?)\]/ig;
            var str_zz = /./ig;
            //匹配字符正则表达式
            let str = null
            let test = null
            if (this.data.emol_textlist.length) {
                for (let i = 0; i < this.data.emol_textlist.length; i++) {
                    test = text.exec(this.data.message)

                }
                str = this.data.message.replace(test[0], '')
                this.data.emol_textlist.pop()

                this.data.message = str
            } else {
                //删除字符
                for (let i = 0; i < this.data.message.length; i++) {
                    test = str_zz.exec(this.data.message)

                }
                str = this.data.message.replace(test[0], '')
                this.data.message = str
            }

            this.setData({
                message: str
            })
        },

        //选择表情分类
        emol_type(e) {

            this.data.emol_index = e.currentTarget.dataset.index
            this.setData({
                emol_index: this.data.emol_index
            })
        },
        //获取光标位置
        cursor(e) {
            this.setData({
                is_up: false,

            })
        },
        //上传图片
        up_img() {
            this.setData({
                is_up: !this.data.is_up,
                is_emol: false,
            })
            // this.afterRead()
        },


        //删除图片
        del(e) {

            this.data.fileList.splice(e.detail.index, 1)
            this.data.updata_num--
            this.setData({
                fileList: this.data.fileList
            })
        },

        uploadToCloud() {
            wx.cloud.init();
            const {
                fileList
            } = this.data;
            if (!fileList.length) {
                wx.showToast({
                    title: '请选择图片',
                    icon: 'none'
                });
            } else {

                const uploadTasks = this.uploadFilePromise(`my-photo${fileList[fileList.length-1].size}.png`, fileList[fileList.length - 1].url);
                Promise.all(uploadTasks)
                    .then(data => {

                        wx.showToast({
                            title: '上传成功',
                            icon: 'none'
                        });
                        const newFileList = data.map(item => (
                            item.fileID

                        ));
                        wx.cloud.getTempFileURL({
                            fileList: newFileList,
                            success: res => {
                                let arr = res.fileList.map(item => ({
                                    url: item.tempFileURL,
                                    name: item.fileID
                                }))
                                this.setData({
                                    cloudPath: data,
                                    fileList: arr
                                });
                            },
                            fail(err) {

                            }
                        })

                    })
                    .catch(e => {
                        wx.showToast({
                            title: '上传失败',
                            icon: 'none'
                        });

                        const newFileList = fileList.map(item => {
                            if (item.status == 'uploading') {
                                return {
                                    url: item.url,
                                    status: 'failed',
                                    message: '上传失败'
                                }
                            } else {
                                return item
                            }

                        });
                        this.setData({

                            fileList: newFileList
                        });


                    });

            }
        },

        //微信云存储
        uploadFilePromise(fileName, chooseResult) {
            wx.cloud.init()
            let that = this
            return wx.cloud.uploadFile({
                cloudPath: fileName + '.png',
                filePath: chooseResult,
                success(res) {
                    wx.cloud.getTempFileURL({
                        fileList: [res.fileID],
                        success: res => {
                            wx.showToast({
                                title: '上传成功',
                                icon: 'none'
                            });

                            that.data.fileList[that.data.fileList.length - 1] = {
                                url: res.fileList[0].tempFileURL,
                                name: res.fileList[0].fileID
                            }

                            that.setData({

                                fileList: that.data.fileList
                            });


                        },
                        fail(err) {
                            wx.showToast({
                                title: '上传失败',
                                icon: 'none'
                            });
                            const newFileList = fileList.map(item => {
                                if (item.status == 'uploading') {
                                    return {
                                        url: item.url,
                                        status: 'failed',
                                        message: '上传失败'
                                    }
                                } else {
                                    return item
                                }

                            });
                            this.setData({

                                fileList: newFileList
                            });
                        }
                    })


                }

            });
        },

        //选择表情包
        xuan_emol(e) {
            let name = e.currentTarget.dataset.emol_value.name.replace(/\[|\]/g, '')
            this.data.emol_textlist.push({
                name: name,
                url: e.currentTarget.dataset.emol_value.url
            })
            //检测光标在哪个位置
            let cursor = this.data.message.length



            //去掉name中的[]

            this.data.message = `${this.data.message}[${this.data.emol_textlist[this.data.emol_textlist.length-1].name}]`,

                this.setData({
                    message: this.data.message
                })

        },
        //打开表情包
        emol_open() {

            this.get_emojis()
            this.setData({
                is_emol: !this.data.is_emol,
                is_up: false,

            })
        },
        //获取表情包
        get_emojis: function (e) {
            let emojis = []
            getEmojis().then(res => {

                for (let i = 0; i < res.data.data.length; i++) {
                    let data = null
                    // data = JSON.stringify()
                    let data_1 = JSON.parse(res.data.data[i])
                    emojis.push(data_1)
                }

                this.setData({
                    emol_list: emojis
                })

            })

            // setTimeout(() => {

            // }, 200)





        },

        //关闭评论
        off_pl() {
            this.triggerEvent('off_pl')
            this.data.emol_open_is = 'false'
            this.data.message = '',
                this.data.emol_textlist = [],
                this.data.fileList = []
            this.setData({
                text_type: 'false',
                is_emol: false,

                message: '',
                fileList: [],
                emol_open_is: 'false'
            })
        },
    }
})